Ext.define('appfe.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.main',

    listen: {
        controller: {
            '#': {
                unmatchedroute: 'onRouteChange'
            }
        }
    },

    routes: {
        ':node': {
            before: 'onRouteBefore',
            action: 'onRouteChange'
        }
    },
    onRouteBefore: function (hashTag, action) {
        console.debug("MainController.onRouteBefore hashTag:", hashTag);
        action.resume();
        //action.stop();
    },
    onRouteChange: function (hashTag) {
        console.debug("MainController.onRouteChange hashTag:", hashTag);
        this.setCurrentView(hashTag, 'onRouteChange');
    },

    lastView: null,

    setCurrentView: function (hashTag) {
        hashTag = (hashTag || '').toLowerCase();
        console.debug("MainController.setCurrentView hashTag:", hashTag);



        var me = this,
            refs = me.getReferences(),
            mainCard = refs.mainCardPanel,
            mainLayout = mainCard.getLayout(),

            view,
            lastView = me.lastView,
            existingItem = mainCard.child('component[routeId=' + hashTag + ']'),
            newView;

        if (hashTag == 'login' || hashTag == 'buyin-point-log-window' || hashTag == 'kline-window') {
            // Ext.create({
            //     xtype: hashTag,
            //     routeId: hashTag
            //     //hideMode: 'offsets'
            // });
            view = hashTag;
        } else {
            navigationList = refs.navigationTreeList;
            store = navigationList.getStore();
            node = store.findNode('routeId', hashTag) || store.findNode('viewType', hashTag);

            if (node && node.get('viewType')) {
                navigationList.setSelection(node);
            }

            view = (node && node.get('viewType')) || 'page404';
        }
        // Kill any previously routed window
        if (lastView && lastView.isWindow) {
            lastView.destroy();
        }

        lastView = mainLayout.getActiveItem();

        if (!existingItem) {
            newView = Ext.create({
                xtype: view,
                routeId: hashTag,  // for existingItem search later
                hideMode: 'offsets'
            });
        }

        if (!newView || !newView.isWindow) {
            // !newView means we have an existing view, but if the newView isWindow
            // we don't add it to the card layout.
            if (existingItem) {
                // We don't have a newView, so activate the existing view.
                if (existingItem !== lastView) {
                    mainLayout.setActiveItem(existingItem);
                }
                newView = existingItem;
            }
            else {
                // newView is set (did not exist already), so add it and make it the
                // activeItem.
                Ext.suspendLayouts();
                mainLayout.setActiveItem(mainCard.add(newView));
                Ext.resumeLayouts(true);
            }
        }
        if (newView.isFocusable(true)) {
            newView.focus();
        }
        me.lastView = newView;
    },

    onNavigationTreeSelectionChange: function (tree, node) {
        var to = node && (node.get('routeId') || node.get('viewType'));
        if (to) {
            this.redirectTo(to);
        }
    },

    onToggleNavigationSize: function () {
        var me = this,
            refs = me.getReferences(),
            navigationList = refs.navigationTreeList,
            wrapContainer = refs.mainContainerWrap,
            collapsing = !navigationList.getMicro(),
            new_width = collapsing ? 64 : 250;

        if (Ext.isIE9m || !Ext.os.is.Desktop) {
            Ext.suspendLayouts();

            refs.senchaLogo.setWidth(new_width);

            navigationList.setWidth(new_width);
            navigationList.setMicro(collapsing);

            Ext.resumeLayouts(); // do not flush the layout here...

            // No animation for IE9 or lower...
            wrapContainer.layout.animatePolicy = wrapContainer.layout.animate = null;
            wrapContainer.updateLayout();  // ... since this will flush them
        }
        else {
            if (!collapsing) {
                // If we are leaving micro mode (expanding), we do that first so that the
                // text of the items in the navlist will be revealed by the animation.
                navigationList.setMicro(false);
            }

            // Start this layout first since it does not require a layout
            refs.senchaLogo.animate({ dynamic: true, to: { width: new_width } });

            // Directly adjust the width config and then run the main wrap container layout
            // as the root layout (it and its chidren). This will cause the adjusted size to
            // be flushed to the element and animate to that new size.
            navigationList.width = new_width;
            wrapContainer.updateLayout({ isRoot: true });
            navigationList.el.addCls('nav-tree-animating');

            // We need to switch to micro mode on the navlist *after* the animation (this
            // allows the "sweep" to leave the item text in place until it is no longer
            // visible.
            if (collapsing) {
                navigationList.on({
                    afterlayoutanimation: function () {
                        navigationList.setMicro(true);
                        navigationList.el.removeCls('nav-tree-animating');
                    },
                    single: true
                });
            }
        }
    },
    /** 右上角的退出按钮点击 */
    onClickLogoutBtn: function () {
        var me = this;
        Ext.Msg.confirm('注销', '是否确认注销?', function (choice) {
            if (choice === 'yes') {
                Ext.Ajax.request({
                    url: BizHttpAction.logout.url,
                    method: BizHttpAction.logout.method,
                    success: function (response, opts) { },
                    failure: function (response, opt) {
                        alert("数据加载失败，请联系系统管理员");
                    }
                });
                /* Remove the localStorage key/value*/
                localStorage.removeItem('TutorialLoggedIn');
                window.location.href = "#login";
                //window.location.hash = "#login"; //等效
            }
        }, this);
    },
    onMainViewRender: function () {
        if (!window.location.hash) {
            this.redirectTo("home");
        }
    },
    afterMainViewRender: function () {
        console.debug("MainController.afterMainViewRender:空事件无处理");
    },
    onRouteChange: function (id) {
        this.setCurrentView(id);
    },

    onSearchRouteChange: function () {
        this.setCurrentView('searchresults');
    },

    onSwitchToModern: function () {
        Ext.Msg.confirm('Switch to Modern', 'Are you sure you want to switch toolkits?',
            this.onSwitchToModernConfirmed, this);
    },

    onSwitchToModernConfirmed: function (choice) {
        if (choice === 'yes') {
            var s = location.search;

            // Strip "?classic" or "&classic" with optionally more "&foo" tokens
            // following and ensure we don't start with "?".
            s = s.replace(/(^\?|&)classic($|&)/, '').replace(/^\?/, '');

            // Add "?modern&" before the remaining tokens and strip & if there are
            // none.
            location.search = ('?modern&' + s).replace(/&$/, '');
        }
    },

    onEmailRouteChange: function () {
        this.setCurrentView('email');
    },
    /**
     * 主面板渲染后执行初始化的一些操作
     */
    onBoxReady: function () {
        console.debug("MainController.onBoxReady:主面板渲染后执行初始化数据操作,加载菜单(根据hashTag路由到对应的视图),加载用户信息,设置一个时钟");
        var me = this;
        var thisModel = me.getViewModel();
        // //加载菜单信息
        // Ext.suspendLayouts();
        // var navTreeList = me.getView().lookup('navTreeList');
        // Ext.Ajax.request({
        //     url: "data/json/navTreeData.json",
        //     method: "GET",
        //     async: false,
        //     success: function (response, opts) {
        //         var respObj = Ext.JSON.decode(response.responseText);
        //         if (respObj.success == true) {
        //             var treeRoot = navTreeList.getStore().getRoot();
        //             treeRoot.removeAll();
        //             treeRoot.appendChild(respObj.data);
        //             //treeRoot.expandChildren(true);
        //             //navTreeList.setSelection(navTreeList.getStore().getRoot().childNodes[1].childNodes[0]);
        //             // treeRoot.appendChild({
        //             //     id: 1,
        //             //     text: 'Login登陆页',
        //             //     iconCls: 'x-fa fa-check',
        //             //     routeId: 'login',
        //             //     url: 'auth.Login'
        //             // });
        //             var urlHash = window.location.hash;
        //             if (window.location.hash) {
        //                 var urlHash = window.location.hash;
        //                 //me.redirectTo(urlHash.substring(1));
        //                 me.setCurrentView(urlHash.substring(1), 'onBoxReady');
        //             }
        //         } else {
        //             Ext.MessageBox.alert("提示", respObj.message);
        //         }
        //     },
        //     failure: function (response, opt) {
        //         alert("数据加载失败，请联系系统管理员");
        //     }
        // });
        // Ext.resumeLayouts(true);
        //加载登录用户基本信息
        Ext.Ajax.request({
            url: BizHttpAction.userinfo.url,
            method: BizHttpAction.userinfo.method,
            success: function (response, opts) {
                var respObj = Ext.JSON.decode(response.responseText);
                if (respObj.success) {
                    thisModel.set('user.username', respObj.data.username);
                    thisModel.set('user.displayname', respObj.data.displayname);
                    var statusbar = Ext.getCmp("msg-statusbar");
                    statusbar.setStatus({
                        text: '<span style="color:green;font-weight:bold;">上次登录时间:' + respObj.data.lastlogintime + "</span>",
                        iconCls: "x-status-valid",
                        clear: 3000 //Modified By Wanghaitao 采用自动消失的设置，正确信息设置为3秒，如果设置为false则不自动消失，如果设置为true则使用autoClear的设置值
                    });
                } else {
                    Ext.Msg.alert("提示", respObj.message);
                }
            },
            failure: function (response, opt) {
                alert("数据加载失败，请联系系统管理员");
            }
        });

        this.chartTaskRunner = new Ext.util.TaskRunner();
        this.chartTaskRunner.start({
            run: function () {
                thisModel.set('clockTip', Ext.Date.format(new Date(), 'Y-m-d H:i:s'));
            },
            interval: 1000
        });
    },
    /**
     * 弹出一个浏览器通知, 
     * Chrome只有https才能弹出
     * 本地locahost或是127.0.0.1需要做如下配置
     * chrome://flags/下查找"Enable native notifications", 设置为disabling 
     */
    fireNotification: function () {
        var myviewmodel = this.getView().getViewModel();
        var msg = '这是一个H5的Notification[点击查看]';
        var random = "?sds" + Math.random();
        var url = 'http://www.baidu.com';
        var smallImg = 'resources/images/liuji.jpg';
        var normalImg = 'resources/images/liuji4.jpg';

        var options = {
            dir: 'auto',
            body: msg,
            icon: smallImg,
            image: normalImg,
            tag: random,
            data: url
        };

        if ((!!window.Notification || window.mozNotification || window.webkitNotification) && Notification.permission !== "denied") {
            Notification.requestPermission(function (status) { // 请求权限
                if (status === 'granted') {
                    // 弹出一个通知
                    var notify = new Notification('通知标题', options);
                    //onshow函数在消息框显示时会被调用, 可以做一些数据记录及定时操作等  
                    notify.onshow = function () {
                        // 两秒后关闭通知
                        //setTimeout(notify.close.bind(notify), 5000); 
                        setTimeout(function () { notify.close(); }, 5000);
                    };
                    //消息框被点击时被调用, 可以打开相关的视图，同时关闭该消息框等操作  
                    notify.onclick = function () {
                        //do something useful  
                        console.debug('notify', notify);
                        console.debug('notify.tag', notify.tag);
                        console.debug('notify.title', notify.title);
                        console.debug('notify.body', notify.body);
                        console.debug('notify.data', notify.data);
                        //ViewModel赋值
                        //myviewmodel.set('user.name', msg);
                        //弹窗打开一个网页
                        //window.open(notify.data + notify.tag);
                        //打开一个模块
                        //me.loadModule('chart.stock.Stock', 'STOCK');
                        me.redirectTo('statist-buyinpoint');
                        notify.close();
                    };
                    //一个消息框关闭时onclose函数会被调用  
                    notify.onclose = function () {
                        console.debug("HTML5桌面消息关闭!!!");
                    };
                    //当有错误发生时会onerror函数会被调用  
                    //如果没有granted授权，创建Notification对象实例时，也会执行onerror函数  
                    notify.onerror = function () {
                        console.debug("HTML5桌面消息出错!!!");
                    };
                }
            });
        } else {
            console.debug("您的浏览器不支持桌面消息");
        }
    }
});
